package com.yun.partnerSys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yun.partnerSys.common.ErrorCode;
import com.yun.partnerSys.contant.UserConstant;
import com.yun.partnerSys.mapper.UserMapper;
import com.yun.partnerSys.model.domain.User;
import com.yun.partnerSys.service.UserService;
import com.yun.partnerSys.utils.AlgorithmUtils;
import com.yun.partnerSys.utils.AliOssUtil;
import com.yun.partnerSys.exception.BusinessException;
import com.yun.partnerSys.service.FollowRelationshipService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import org.apache.commons.math3.util.Pair;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 用户服务实现类
 *
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Resource
    private AliOssUtil aliOssUtil;


    @Resource
    @Lazy
    private FollowRelationshipService followRelationshipService;
    // https://www.code-nav.cn/

    /**
     * 盐值，混淆密码
     */
    private static final String SALT = "yupi";

    /**
     * 用户注册
     *
     * @param userAccount   用户账户
     * @param userPassword  用户密码
     * @param checkPassword 校验密码
     * @param planetCode    星球编号
     * @return 新用户 id
     */
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword, String planetCode) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, planetCode)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        if (planetCode.length() > 5) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "星球编号过长");
        }
        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            return -1;
        }
        // 密码和校验密码相同
        if (!userPassword.equals(checkPassword)) {
            return -1;
        }
        // 账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
        }
        // 星球编号不能重复
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("planetCode", planetCode);
        count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "编号重复");
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 3. 插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setPlanetCode(planetCode);
        boolean saveResult = this.save(user);
        if (!saveResult) {
            return -1;
        }
        return user.getId();
    }

    /**
     * 用户登录
     *
     * @param userAccount  用户账户
     * @param userPassword 用户密码
     * @param request
     * @return 脱敏后的用户信息
     */
    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return null;
        }
        if (userAccount.length() < 4) {
            return null;
        }
        if (userPassword.length() < 8) {
            return null;
        }
        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            return null;
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        // 用户不存在
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            return null;
        }
        // 3. 用户脱敏
        User safetyUser = getSafetyUser(user);
        // 4. 记录用户的登录态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, safetyUser);
        return safetyUser;
    }

    /**
     * 用户脱敏
     *
     * @param originUser
     * @return
     */
    @Override
    public User getSafetyUser(User originUser) {
        if (originUser == null) {
            return null;
        }
        User safetyUser = new User();
        safetyUser.setId(originUser.getId());
        safetyUser.setUsername(originUser.getUsername());
        safetyUser.setUserAccount(originUser.getUserAccount());
        safetyUser.setAvatarUrl(originUser.getAvatarUrl());
        safetyUser.setGender(originUser.getGender());
        safetyUser.setPhone(originUser.getPhone());
        safetyUser.setEmail(originUser.getEmail());
        safetyUser.setPlanetCode(originUser.getPlanetCode());
        safetyUser.setUserRole(originUser.getUserRole());
        safetyUser.setUserStatus(originUser.getUserStatus());
        safetyUser.setCreateTime(originUser.getCreateTime());
        safetyUser.setTags(originUser.getTags());
        safetyUser.setProfile(originUser.getProfile());
        return safetyUser;
    }

    /**
     * 用户注销
     *
     * @param request
     */
    @Override
    public int userLogout(HttpServletRequest request) {
        // 移除登录态
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return 1;
    }


    @Override
    public List<User> searchUserByTags(List<String> tagNameList, User loginUser) {
        //判断是否为空
        if(CollectionUtils.isEmpty(tagNameList)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 1.数据库查询的方法
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        for(String tagName : tagNameList){
            queryWrapper = queryWrapper.like("tags",tagName);
        }
        queryWrapper.ne("id",loginUser.getId());
        List<User> userList = userMapper.selectList(queryWrapper);

        //利用函数式接口对userList进行脱敏，并返回。
        return userList.stream().map(this::getSafetyUser).collect(Collectors.toList());


        /*//2.在内存中查询的方法
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //查询出所有用户
        List<User> userList = userMapper.selectList(queryWrapper);

        Gson gson = new Gson();
        return userList.stream().filter(user -> {
            String tagsStr = user.getTags();
            if(StringUtils.isBlank(tagsStr)){
                return false;
            }
            //使用Gson将字符串转化为json
            Set<String> tempTagNameSet = gson.fromJson(tagsStr,new TypeToken<Set<String>>(){}.getType());
            if(CollectionUtils.isEmpty(tempTagNameSet)){
                throw new BusinessException(ErrorCode.NULL_ERROR);
            }
            for(String tagName : tagNameList){
                if(!tempTagNameSet.contains(tagName)){
                    return false;
                }
            }
            return true;
        }).map(this::getSafetyUser).collect(Collectors.toList());*/
    }

    @Override
    public User getLoginUser(HttpServletRequest request) {
        if(request==null){
            return null;
        }
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);

        if(userObj==null){
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        return (User) userObj;
    }

    @Override
    public int updateUser(User user, User loginUser) {
        Long userId = user.getId();
        if(userId == null || userId<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //todo 补充校验

        //如果是管理员可以修改任何人
        //如果不是，则只能修改自己
        if(!isAdmin(loginUser) && !userId.equals(loginUser.getId())){
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        User oldUser = getById(userId);
        if(oldUser == null){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        return userMapper.updateById(user);
    }


    /**
     * 是否为管理员
     *
     * @param request
     * @return
     */
    @Override
    public boolean isAdmin(HttpServletRequest request) {
        // 仅管理员可查询
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User user = (User) userObj;
        return user != null && user.getUserRole() == UserConstant.ADMIN_ROLE;
    }

    /**
     * 是否为管理员
     *
     * @param loginUser
     * @return
     */
    @Override
    public boolean isAdmin(User loginUser) {
        return loginUser != null && loginUser.getUserRole() == UserConstant.ADMIN_ROLE;
    }

    @Override
    public List<User> matchUsers(long num, User loginUser) {
        //判断缓存中是否以及储存信息
        String redisKey = String.format("yupao:user:match:%s", loginUser.getId());
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        List<User> userList = (List<User>) valueOperations.get(redisKey);
        if(userList != null && userList.size() >0){
            return userList;
        }

        //查询所有用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id","tags");
        queryWrapper.isNotNull("tags");
        List<User> allUserList = this.list(queryWrapper);

        //把登陆用户的tags转为List
        String tags= loginUser.getTags();
        Gson gson = new Gson();
        List<String> tagsList = gson.fromJson(tags, new TypeToken<List<String>>() {}.getType());

        // 用户列表的下标 => 相似度
        List<Pair<User,Long>> list = new ArrayList<>();

        // 依次计算所有用户和当前用户的相似度
        for(int i=0;i<allUserList.size();i++){
            User user = allUserList.get(i);
            String userTags = user.getTags();
            // 无标签或者为当前用户自己
            if(StringUtils.isBlank(userTags) || user.getId().equals(loginUser.getId())){
                continue;
            }
            List<String> userTagList = gson.fromJson(userTags, new TypeToken<List<String>>() {
            }.getType());

            // 计算分数
            long distance = AlgorithmUtils.minDistance(tagsList, userTagList);
            list.add(new Pair<User, Long>(user,distance));
        }
        // 按编辑距离由小到大排序
        List<Pair<User, Long>> topUserPairList = list.stream()
                .sorted((a, b) -> (int) (a.getValue() - b.getValue()))
                .limit(num)
                .collect(Collectors.toList());

        List<Long> topUserIdList = topUserPairList.stream().map(pair -> pair.getKey().getId()).collect(Collectors.toList());
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.in("id",topUserIdList);

        //用户数据脱敏
        //List中实际只有一个元素
        Map<Long, List<User>> userIdListMap = this.list(userQueryWrapper)
                .stream()
                .map(user -> getSafetyUser(user))
                .collect(Collectors.groupingBy(User::getId));
        List<User> finalUserList = new ArrayList<>();

        //利用原id排序保持顺序不会乱了
        for(Long userId : topUserIdList){
            User user = userIdListMap.get(userId).get(0);
//            boolean isFollowed = followRelationshipService.isFans(user.getId(), loginUser);
//            user.setIsFollowed(isFollowed);
            finalUserList.add(user);
        }

        //写缓存
        try {
            valueOperations.set(redisKey,finalUserList,30, TimeUnit.SECONDS);
        }catch (Exception e){
            log.error("redis set error",e);
        }

        return finalUserList;
    }

    /**
     * 根据id获取用户
     *
     * @param id 用户id
     * @return
     */
    @Override
    public User getUserById(long id) {
        User user = this.getById(id);
        return this.getSafetyUser(user);
    }

    @Override
    public Page<User> getRecommend(long pageSize, long pageNum, User loginUser) {
        //判断缓存中是否以及储存信息
        String redisKey = String.format("yupao:user:recommend:%s:%s", loginUser.getId(),pageNum);
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        Page<User> userPage = (Page<User>) valueOperations.get(redisKey);
        if(userPage != null){
            return userPage;
        }

        //否则查询数据库
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.ne("id",loginUser.getId());
        userPage = this.page(new Page<>(pageNum, pageSize), queryWrapper);
        List<User> userList = userPage.getRecords();

        //用户数据脱敏
        userList.forEach(user -> {
            user.setUserPassword("");
            if(user.getProfile() == null || user.getProfile() == ""){
                user.setProfile("这个用户很懒，没有留下任何东西");
            }
        });

        userPage.setRecords(userList);

        //写缓存
        try {
            valueOperations.set(redisKey,userPage,30, TimeUnit.SECONDS);
        }catch (Exception e){
            log.error("redis set error",e);
        }
        return userPage;
    }

    /**
     * 更新用户标签
     *
     * @param tags      新用户标签
     * @param loginUser 当前登录用户
     * @return
     */
    @Override
    public Boolean updateTags(String tags, User loginUser) {
        // 判断标签格式
        if (tags == null || !(tags.startsWith("[") && tags.endsWith("]"))) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        User newUser = new User();
        BeanUtils.copyProperties(loginUser, newUser);
        newUser.setTags(tags);

        // 用户最多选择10个标签
        Gson gson = new Gson();
        Type listType = new TypeToken<List<String>>() {
        }.getType();
        List<String> list = gson.fromJson(newUser.getTags(), listType);
        if (list.size() > 10) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户最多选择10个标签");
        }

        boolean isSuccess = this.updateById(newUser);
        return isSuccess;
    }

    /**
     * 用户头像上传
     *
     * @param file 头像
     * @return
     */
    @Override
    public String uploadUserAvatarUrl(MultipartFile file, User loginUser) {

        if (file.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "未上传头像");
        }
        log.info("文件上传：{}", file);

        try {
            // 获取原始文件名
            String originalFilename = file.getOriginalFilename();
            // 截取原始文件名的后缀
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 构造新文件名称
            String objectName = UUID.randomUUID() + extension;
            // 文件的请求路径
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            User newUser = new User();
            BeanUtils.copyProperties(loginUser, newUser);
            newUser.setAvatarUrl(filePath);
            userMapper.updateById(newUser);
            return filePath;
        } catch (IOException e) {
            log.error("文件上传失败：{}", e);
        }
        return null;
    }

}

